package com.zhang;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Before;
import org.junit.Test;


/**
 * 测试认证过程
 */
public class AuthenticationTest {

     SimpleAccountRealm simpleAccountRealm=new SimpleAccountRealm();
    //简单的Realm做演示
     @Before
    public  void  addUser()
    {
        //获取用户登录的账户密码
        simpleAccountRealm.addAccount("zhangsan","123");
    }

    @Test
    public void testAuthentication()
    {
//        1.构建SecurityManager环境
        DefaultSecurityManager defaultSecurityManager= new DefaultSecurityManager();
        defaultSecurityManager.setRealm(simpleAccountRealm);
//        2.主体提交认证请求
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject=SecurityUtils.getSubject();
//        3.获取认证数据（从数据库）
        UsernamePasswordToken token =new UsernamePasswordToken("zhangsan","123");
        System.out.println("是否认证的结果："+subject.isAuthenticated());
       subject.login(token);
        System.out.println("是否认证的结果："+subject.isAuthenticated());
        subject.logout();
        System.out.println("是否认证的结果："+subject.isAuthenticated());
    }
}
